﻿#include "amplstepwindow.h"
#include "ui_amplstepwindow.h"
#include <mainwindow.h>
#include <eqptinfo.h>
extern intListener doorStatus;
amplStepWindow::amplStepWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::amplStepWindow)
{
    ui->setupUi(this);
    setWindowIcon(QIcon(":/pic/picture/kafavicon.ico"));

    label<<"Id"<<"ProgramId"<<"StepNum"<<"Temperature"<<"Rate"<<"ExecutionTime"<<"IsCollect"<<"CycleNumber"<<"CycleNum";
    QStringList  labels;
    labels<<QStringLiteral("ID") <<QStringLiteral("ProgramId")<< QStringLiteral("步骤编号") << QStringLiteral("温度(°C)")<<QStringLiteral("速率(°/s)") << QStringLiteral("时间(s)")<<QStringLiteral("是否采集")<<QStringLiteral("循环编号")<<QStringLiteral("循环数")<<QStringLiteral("操作");
    ui->tableWidget->setColumnCount(10);
    ui->tableWidget->setHorizontalHeaderLabels(labels);
    ui->tableWidget->resizeColumnsToContents(); //根据内容调整列宽
    ui->tableWidget->setColumnHidden(0, true); // 隐藏第1列
    ui->tableWidget->setColumnHidden(1, true); // 隐藏第1列
    ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget->verticalHeader()->setHidden(true);
    ui->tableWidget->setInputMethodHints(Qt::ImhHiddenText);

    QRegExp regExp("^[\u4E00-\u9FA5a-zA-Z0-9_\\+\\-\\\\ \\/ \\( \\) \\.]+$");
    QRegExpValidator *validator = new QRegExpValidator(regExp, this);
    ui->programeName->setValidator(validator);
    ui->programeName->setMaxLength(30);

    ui->lineEdit->setValidator(validator);
    ui->lineEdit->setMaxLength(30);
    ui->pushButton_5->setVisible(false);
}

amplStepWindow::~amplStepWindow()
{
    delete ui;
}

void amplStepWindow::showEvent(QShowEvent *event){
    logClient=loghelper::getInstance();
    tcpClient=TcpClient::getInstance();

    ui->programeName->setText("");
    ui->lineEdit->setText("");
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);

    if(amplGuid.isNull() ||amplGuid.isEmpty()){
        amplGuid= common->GetGuid();
    }
    if(MainWindow::experimentStatus.get()==4){
        QString sql=QString("Select programName,Memo from AmplProgramTemp where id='%1'").arg(amplGuid);
        query.exec(sql);
        while (query.next()) {
            ui->programeName->setText(query.value("ProgramName").toString());
            ui->lineEdit->setText(query.value("Memo").toString());
        }

    }else{
        QString sql=QString("Select programName,Memo from AmplProgram where id='%1'").arg(amplGuid);
        query.exec(sql);
        while (query.next()) {
            ui->programeName->setText(query.value("ProgramName").toString());
            ui->lineEdit->setText(query.value("Memo").toString());
        }

    }

    //查看可编辑 查看不可编辑 新建可编辑
    if(MainWindow::experimentStatus.get()==1 ||MainWindow::experimentStatus.get()==4)
    {
        ui->programeName->setReadOnly(true);
        ui->lineEdit->setReadOnly(true);
        ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
        ui->pushButton_4->setEnabled(false);
        ui->pushButton_5->setEnabled(false);
        ui->label_8->setText("查看程序");
    }
    else
    {
        ui->programeName->setReadOnly(false);
        ui->lineEdit->setReadOnly(false);
        ui->tableWidget->setEditTriggers(QAbstractItemView::CurrentChanged);
        ui->pushButton_4->setEnabled(true);
        ui->pushButton_5->setEnabled(true);
        if(isReadStatus==0){
            ui->label_8->setText("新建程序");
        }else{
            ui->label_8->setText("查看程序");
        }
    }

    RefreshTableData();
    for(int i=0;i<ui->tableWidget->rowCount();i++){
        ui->tableWidget->setRowHeight(i, 50);
    }
}

void amplStepWindow::on_pushButton_2_clicked()
{
    this->close();

    if(MainWindow::experimentStatus.get()==1)
    {
        emit changeExpProWindow();
    }
    else if(MainWindow::experimentStatus.get() == 4){
        emit changeExperimentInfoWindow();
    }
    else if(MainWindow::experimentStatus.get()==0){
        if(isReadStatus==0 || isReadStatus==1){
            emit changeAmplProWindow();
        }
        else
        {
            emit changeExperimentInfoWindow();
        }
    }
    else if(MainWindow::experimentStatus.get() == 5){
        emit changeExperimentInfoWindow();
    }
}

void amplStepWindow::on_pushButton_clicked()
{
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);

    QString sql=QString("Insert into AmplStep values('%1','%2','1','','','','否','','')").arg(common->GetGuid(),amplGuid);
    query.exec(sql);

    RefreshTableData();
}

void amplStepWindow::RefreshTableData(){
    ui->tableWidget->blockSignals(true);

    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);

    double dataNum=0;
    QString sql;
    if(MainWindow::experimentStatus.get()==4){
        sql=QString("Select count(*) as Num from AmplStepTemp where ProgramId='%1' order by StepNum").arg(amplGuid);
        query.exec(sql);
        while (query.next()) {
            dataNum=query.value("Num").toDouble();
        }
    }else{
        sql=QString("Select count(*) as Num from AmplStep where ProgramId='%1' order by StepNum").arg(amplGuid);
        query.exec(sql);
        while (query.next()) {
            dataNum=query.value("Num").toDouble();
        }
    }

    if(dataNum>0){
        if(MainWindow::experimentStatus.get()==4){
            sql=QString("Select * from AmplStepTemp where ProgramId='%1' order by StepNum").arg(amplGuid);

        }else{
            sql=QString("Select * from AmplStep where ProgramId='%1' order by StepNum").arg(amplGuid);
        }
        query.exec(sql);
        ui->tableWidget->setRowCount(0);
        int rowNum=0;

        while (query.next()) {
            ui->tableWidget->insertRow(rowNum);
            ui->tableWidget->setRowHeight(rowNum, 50);

            for (int l=0;l<label.length();l++) {
                if(l==6){
                    QComboBox *comboBox = new QComboBox();
                    comboBox->setStyleSheet(
                                "QComboBox {"
                                "    background-color: white; /* 设置背景颜色为白色 */"
                                "    border: none; /* 可选：设置边框颜色，如果需要的话 */"
                                "    border-radius: 4px; /* 可选：设置边框圆角 */"
                                "}"
                                /* 注意：这里没有直接修改下拉箭头的样式，因为它通常是由Qt主题或操作系统控制的 */
                                );
                    comboBox->addItem("是");
                    comboBox->addItem("否");
                    comboBox->setCurrentText(query.value(label[l]).toString());
                    if(MainWindow::experimentStatus.get()==1||MainWindow::experimentStatus.get()==4)
                    {
                        comboBox->setEnabled(false);
                    }
                    ui->tableWidget->setCellWidget(rowNum, 6, comboBox);
                    QObject::connect(comboBox,&QComboBox::currentTextChanged,this,[&](QString newString){
                        int rowNum= this->ui->tableWidget->currentIndex().row();
                        QString id = ui->tableWidget->item(rowNum,0)->text();//取出当前行第1列内容

                        if(newString=="是"){
                            QSqlDatabase db = dbHelper::openConnection();
                            QSqlQuery query(db);

                            QString sql=QString("Select Count(*) Sum From AmplStep where ProgramId='%1' and IsCollect='是' and id<>'%2'").arg(amplGuid,id);

                            query.exec(sql);
                            bool canRef=false;

                            while (query.next()) {
                                canRef=query.value("Sum").toInt()>0;
                            }
                            if(canRef){
                                tcts *tctsWindow = new tcts();
                                tctsWindow->infochange("提示","info","当前已有采集数据步骤,是否确认将当前步骤改为采集数据步骤",true,true);
                                tctsWindow->show();

                                connect(tctsWindow->ui->pushButton_2, &QPushButton::clicked,[this](){
                                    int rowNum= this->ui->tableWidget->currentIndex().row();
                                    QString id = ui->tableWidget->item(rowNum,0)->text();//取出当前行第1列内容
                                    QSqlDatabase db = dbHelper::openConnection();
                                    QSqlQuery query(db);

                                    QString sql=QString("Update AmplStep set IsCollect='否' where ProgramId='%1'").arg(amplGuid);
                                    query.exec(sql);

                                    sql=QString("Update AmplStep set IsCollect='是' where id='%1'").arg(id);
                                    query.exec(sql);
                                    RefreshTableData();

                                });
                                connect(tctsWindow->ui->pushButton, &QPushButton::clicked,[this](){
                                    int rowNum= this->ui->tableWidget->currentIndex().row();
                                    QString id = ui->tableWidget->item(rowNum,0)->text();//取出当前行第1列内容
                                    QSqlDatabase db = dbHelper::openConnection();
                                    QSqlQuery query(db);

                                    QString sql=QString("Update AmplStep set IsCollect='否' where id='%1'").arg(id);
                                    query.exec(sql);
                                    RefreshTableData();
                                });
                            }else {
                                sql=QString("Update AmplStep set IsCollect='是' where id='%1'").arg(id);
                                query.exec(sql);
                                RefreshTableData();
                            }
                        }else{
                            QSqlDatabase db = dbHelper::openConnection();
                            QSqlQuery query(db);

                            QString sql=QString("Update AmplStep set IsCollect='否' where id='%1'").arg(id);
                            query.exec(sql);
                            RefreshTableData();
                        }
                    });
                }
                QTableWidgetItem *item = new QTableWidgetItem(query.value(label[l]).toString());
                ui->tableWidget->setItem(rowNum, l, item);
                ui->tableWidget->item(rowNum,l)->setTextAlignment(Qt::AlignCenter);
            }
            QPushButton *delBtn = new QPushButton();
            delBtn->setText("删除");
            delBtn->setMinimumSize(40,30);

            QPushButton *addBtn=new QPushButton();
            addBtn->setText("添加");
            addBtn->setMinimumSize(40,30);

            if(MainWindow::experimentStatus.get()==1||MainWindow::experimentStatus.get()==4){
                delBtn->setEnabled(false);
                addBtn->setEnabled(false);
            }
            QWidget *tmp_widget = new QWidget();
            QHBoxLayout *tmp_layout = new QHBoxLayout(tmp_widget);
            tmp_layout->addWidget(delBtn);
            tmp_layout->addWidget(addBtn);
            tmp_layout->setMargin(0);
            ui->tableWidget->setCellWidget(rowNum,9,tmp_widget);

            connect(delBtn, SIGNAL(clicked()), this,SLOT(delBtnClicked()));
            connect(addBtn, SIGNAL(clicked()), this,SLOT(addBtnClicked()));
            rowNum++;
        }
    }else {
        QString guid=common->GetGuid();
        sql=QString("Insert into AmplStep values("
                    "'%1',"
                    "'%2',"
                    "'1',"
                    "'','','','否','0','1')").arg(guid,amplGuid);
        query.exec(sql);

        ui->tableWidget->setRowCount(0);
        ui->tableWidget->insertRow(0);

        for (int l=0;l<label.length();l++) {
            if(l==0){
                QTableWidgetItem *item=new QTableWidgetItem(guid);
                ui->tableWidget->setItem(0, 0, item);
                ui->tableWidget->item(0,0)->setTextAlignment(Qt::AlignCenter);
            }
            else if(l==1){
                QTableWidgetItem *item=new QTableWidgetItem(amplGuid);
                ui->tableWidget->setItem(0, 1, item);
                ui->tableWidget->item(0,1)->setTextAlignment(Qt::AlignCenter);
            }
            else if(l==2){
                QTableWidgetItem *item = new QTableWidgetItem("1");
                ui->tableWidget->setItem(0, 2, item);
                ui->tableWidget->item(0,2)->setTextAlignment(Qt::AlignCenter);
            }
            else if(l==6){
                QComboBox *comboBox = new QComboBox();
                comboBox->setStyleSheet(
                            "QComboBox {"
                            "    background-color: white; /* 设置背景颜色为白色 */"
                            "    border: none; /* 可选：设置边框颜色，如果需要的话 */"
                            "    border-radius: 4px; /* 可选：设置边框圆角 */"
                            "}"
                            /* 注意：这里没有直接修改下拉箭头的样式，因为它通常是由Qt主题或操作系统控制的 */
                            );
                comboBox->addItem("是");
                comboBox->addItem("否");
                comboBox->setCurrentText("否");
                if(MainWindow::experimentStatus.get()==1||MainWindow::experimentStatus.get()==4)
                {
                    comboBox->setEnabled(false);
                }
                ui->tableWidget->setCellWidget(0, 6, comboBox);

                QObject::connect(comboBox,&QComboBox::currentTextChanged,this,[&](QString newString){
                    int rowNum= this->ui->tableWidget->currentIndex().row();
                    QString id = ui->tableWidget->item(rowNum,0)->text();//取出当前行第1列内容
                    if(newString=="是"){
                        QSqlDatabase db = dbHelper::openConnection();
                        QSqlQuery query(db);

                        QString sql=QString("Select Count(*) Sum From AmplStep where ProgramId='%1' and IsCollect='是' and id<>'%2'").arg(amplGuid,id);

                        query.exec(sql);
                        bool canRef=false;

                        while (query.next()) {
                            canRef=query.value("Sum").toInt()>0;
                        }

                        if(canRef){
                            tcts *tctsWindow = new tcts();
                            tctsWindow->infochange("提示","info","当前已有采集数据步骤,是否确认将当前步骤改为采集数据步骤",true,true);
                            tctsWindow->show();

                            connect(tctsWindow->ui->pushButton_2, &QPushButton::clicked,[this](){
                                QSqlDatabase db = dbHelper::openConnection();
                                QSqlQuery query(db);
                                QString sql=QString("Update AmplStep set IsCollect='否' where ProgramId='%1'").arg(amplGuid);
                                query.exec(sql);
                                int rowNum= this->ui->tableWidget->currentIndex().row();
                                QString id = ui->tableWidget->item(rowNum,0)->text();//取出当前行第1列内容

                                sql=QString("Update AmplStep set IsCollect='是' where id='%1'").arg(id);
                                query.exec(sql);
                                RefreshTableData();
                            });

                            connect(tctsWindow->ui->pushButton, &QPushButton::clicked,[this](){
                                QSqlDatabase db = dbHelper::openConnection();
                                QSqlQuery query(db);
                                int rowNum= this->ui->tableWidget->currentIndex().row();
                                QString id = ui->tableWidget->item(rowNum,0)->text();//取出当前行第1列内容
                                QString sql=QString("Update AmplStep set IsCollect='否' where id='%1'").arg(id);
                                query.exec(sql);

                                RefreshTableData();
                            });
                        }else {
                            sql=QString("Update AmplStep set IsCollect='是' where id='%1'").arg(id);
                            query.exec(sql);
                            RefreshTableData();
                        }
                    }
                });
            }
            else if(l==7){
                QTableWidgetItem *item=new QTableWidgetItem("0");
                ui->tableWidget->setItem(0, 7, item);
                ui->tableWidget->item(0,7)->setTextAlignment(Qt::AlignCenter);
            }
            else if(l==8){
                QTableWidgetItem *item=new QTableWidgetItem("1");
                ui->tableWidget->setItem(0, 8, item);
                ui->tableWidget->item(0,8)->setTextAlignment(Qt::AlignCenter);
            }else {
                QTableWidgetItem *item = new QTableWidgetItem("");
                ui->tableWidget->setItem(0, l, item);
                ui->tableWidget->item(0,l)->setTextAlignment(Qt::AlignCenter);
            }
        }

        QPushButton *delBtn = new QPushButton();
        delBtn->setText("删除");
        delBtn->setMinimumSize(40,30);

        QPushButton *addBtn=new QPushButton();
        addBtn->setText("添加");
        addBtn->setMinimumSize(40,30);
        if(MainWindow::experimentStatus.get()==1||MainWindow::experimentStatus.get()==4)
        {
            delBtn->setEnabled(false);
            addBtn->setEnabled(false);
        }
        QWidget *tmp_widget = new QWidget();
        QHBoxLayout *tmp_layout = new QHBoxLayout(tmp_widget);
        tmp_layout->addWidget(delBtn);
        tmp_layout->addWidget(addBtn);
        tmp_layout->setMargin(0);
        ui->tableWidget->setCellWidget(0,9,tmp_widget);

        connect(delBtn, SIGNAL(clicked()), this,SLOT(delBtnClicked()));
        connect(addBtn, SIGNAL(clicked()), this,SLOT(addBtnClicked()));
    }
    ui->tableWidget->blockSignals(false);
}

void amplStepWindow::addBtnClicked(){

    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);

    QPushButton *btn = (QPushButton*)sender();
    QWidget *w_parent = (QWidget*)btn->parent();
    int x = w_parent->frameGeometry().x();
    int y = w_parent->frameGeometry().y();
    QModelIndex index = ui->tableWidget->indexAt(QPoint(x,y));

    QString stepNum = ui->tableWidget->item(index.row(),2)->text();//取出当前行第1列内容
    int finalStepNum=stepNum.toInt()+1;
    QString sql=QString("Update AmplStep set StepNum=StepNum+1 where "
                        "ProgramId='%1' and StepNum>=%2").arg(amplGuid,QString::number(finalStepNum));
    query.exec(sql);

    sql=QString("Insert into AmplStep values("
                "'%1',"
                "'%2',"
                "'%3',"
                "'','','','否','0','1')").arg(common->GetGuid(),amplGuid,QString::number(finalStepNum));
    query.exec(sql);

    RefreshTableData();
}

void amplStepWindow::delBtnClicked(){
    QPushButton *btn = (QPushButton*)sender();
    QWidget *w_parent = (QWidget*)btn->parent();
    int x = w_parent->frameGeometry().x();
    int y = w_parent->frameGeometry().y();
    QModelIndex index = ui->tableWidget->indexAt(QPoint(x,y));

    id = ui->tableWidget->item(index.row(),0)->text();//取出当前行第1列内容

    stepNum = ui->tableWidget->item(index.row(),2)->text();//取出当前行第1列内容

    tcts *tctsWindow = new tcts();
    tctsWindow->infochange("提示","info","确认删除当前步骤",true,true);
    tctsWindow->show();

    connect(tctsWindow->ui->pushButton_2, &QPushButton::clicked,[this](){
        QSqlDatabase db = dbHelper::openConnection();
        QSqlQuery query(db);

        if(ui->tableWidget->rowCount()==1)
        {
            tcts *tctsWindow = new tcts();
            tctsWindow->infochange("提示","info","至少需要保留一个步骤",false,true);
            tctsWindow->show();
        }
        else
        {
            QString sql=QString("Update AmplStep set StepNum=StepNum-1 where "
                                "ProgramId='%1' and StepNum>=%2").arg(amplGuid,stepNum);
            query.exec(sql);

            sql=QString("Delete from AmplStep where id='%1'").arg(id);
            query.exec(sql);

            RefreshTableData();
        }
    });
}

void amplStepWindow::on_tableWidget_itemChanged(QTableWidgetItem *item)
{
    QString StepNum=ui->tableWidget->item(item->row(),2)->text();
    QString temp=ui->tableWidget->item(item->row(),3)->text();
    QString rate=ui->tableWidget->item(item->row(),4)->text();
    QString executionTime=ui->tableWidget->item(item->row(),5)->text();
    QString CycleNumber=ui->tableWidget->item(item->row(),7)->text();
    QString CycleNum=ui->tableWidget->item(item->row(),8)->text();
    QString id=ui->tableWidget->item(item->row(),0)->text();

    if(!temp.isNull()&&!temp.isEmpty()){
        bool isNum;
        double tempNum=temp.toDouble(&isNum);
        if(isNum)
        {
            if(tempNum>120||tempNum<4){
                ui->tableWidget->item(item->row(),3)->setText("");
                return;
            }

            if(QString::number(tempNum).contains(".")){
                QList<QString> tempList=QString::number(tempNum).split(".");
                if(tempList[1].length()>2){
                    ui->tableWidget->item(item->row(),3)->setText("");
                    return;
                }
            }
        }
        else
        {
            ui->tableWidget->item(item->row(),3)->setText("");
            return;
        }
    }

    if(!executionTime.isNull()&&!executionTime.isEmpty()){
        bool isNum;
        int time=executionTime.toInt(&isNum);
        if(!isNum || time<0){
            ui->tableWidget->item(item->row(),5)->setText("");
            return;
        }
    }

    if(!CycleNumber.isNull()&&!CycleNumber.isEmpty()){
        bool isNum;
        int cycleNumber=CycleNumber.toInt(&isNum);
        if(!isNum || cycleNumber<0)
        {
            ui->tableWidget->item(item->row(),7)->setText("");
            return;
        }else{
            if(cycleNumber!=0 && cycleNumber>StepNum.toInt()){
                ui->tableWidget->item(item->row(),7)->setText("");
                return;
            }
        }
    }

    if(!CycleNum.isNull()&&!CycleNum.isEmpty()){
        bool isNum;
        int cycleNum=CycleNum.toInt(&isNum);
        if(!isNum || cycleNum<0){
            ui->tableWidget->item(item->row(),8)->setText("");
            return;
        }
        else
        {
            if(cycleNum<1 || cycleNum >= 65)
            {
                ui->tableWidget->item(item->row(),8)->setText("");
                return;
            }
        }
    }

    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql=QString("Update AmplStep set "
                        "Temperature='%1',"
                        "ExecutionTime='%2',"
                        "CycleNumber='%3',"
                        "CycleNum='%4',"
                        "StepNum=%6,"
                        "Rate='%7' "
                        "where Id='%5'").arg(temp,executionTime,CycleNumber,CycleNum,id,StepNum,rate);
    query.exec(sql);
}

void amplStepWindow::on_pushButton_4_clicked()
{
    QSqlDatabase db=dbHelper::openConnection();
    QSqlQuery query(db);

    QString sql=QString("SELECT CASE WHEN COUNTNum > 1 AND "
                        "countRule > 0 THEN 1 ELSE 0 END as result "
                        "FROM (SELECT count( * ) countNum "
                        "FROM AmplStep "
                        "WHERE programId = '%1' AND "
                        "Temperature <> '' AND "
                        "ExecutionTime <> ''),("
                        "SELECT count( * ) countRule "
                        "FROM AmplStep "
                        "WHERE programId = '%1' AND "
                        "Temperature <> '' AND ExecutionTime <> '' AND "
                        "CycleNumber > 0 AND CycleNum > 1);").arg(amplGuid);
    query.exec(sql);
    bool rule = false;
    while (query.next()) {
        rule=query.value("Result").toInt()==1;
    }

    if(!rule){
        tcts *tctsWindow = new tcts();
        tctsWindow->infochange("提示","info","至少要包含两个步骤,并且需正确填写温度数据,循环数,循环编号",false,true);
        tctsWindow->show();
        return;
    }


    if(ui->programeName->text().isNull() || ui->programeName->text().isEmpty()){
        tcts *tctsWindow = new tcts();
        tctsWindow->infochange("提示","info","扩增程序名称不能为空",false,true);
        tctsWindow->show();
        return;
    }else{
        sql=QString("Select count(*) countNum From AmplProgram "
                    "where ProgramName='%1' and id<>'%2'").arg(ui->programeName->text(),amplGuid);
        query.exec(sql);
        bool rule = false;
        while (query.next()) {
            rule=query.value("countNum").toInt()!=0;
        }
        if(rule){
            tcts *tctsWindow = new tcts();
            tctsWindow->infochange("提示","info","扩增程序名称不能重复",false,true);
            tctsWindow->show();
            return;
        }

    }

    double StepNum=0;
    double CycleNumber=0;
    double CycleNum=0;
    sql=QString("Select StepNum,CycleNumber,CycleNum "
                "From AmplStep "
                "where programId='%1' and "
                "StepNum=(Select max(StepNum) from AmplStep where ProgramId='%1')").arg(amplGuid);

    query.exec(sql);
    while (query.next()) {
        StepNum=query.value("StepNum").toDouble();
        CycleNumber=query.value("CycleNumber").toDouble();
        CycleNum=query.value("CycleNum").toDouble();
    }

    eqptinfo eqInfo;
    QString addNum=eqInfo.calculateDurationread();

    double duration=0;
    sql=QString("Select sum(ExecutionTime + %4)*%1 as Result from AmplStep where ProgramId='%2' and StepNum>='%3'").arg(QString::number(CycleNum),amplGuid,QString::number(CycleNumber),addNum);
    query.exec(sql);
    while (query.next()) {
        duration+=query.value("Result").toDouble();
    }

    if(StepNum>1){
        sql=QString("Select sum((ExecutionTime + %3)*CycleNum) as Result from AmplStep where ProgramId='%1' and StepNum<'%2'").arg(amplGuid,QString::number(CycleNumber),addNum);
        query.exec(sql);
        while (query.next()) {
            duration+=query.value("Result").toDouble();
        }
    }
    QString durationResult;
    if(duration/3600>1){
        double hour=0;
        double min=0;
        double sec=0;

        std::div_t hourResult = std::div(duration, 3600);
        hour=hourResult.quot;

        std::div_t minResult = std::div(duration-hour*3600,60);
        min=minResult.quot;

        sec=duration-hour*3600-min*60;
        durationResult=QString::number(hour)+"时"+QString::number(min)+"分"+QString::number(sec)+"秒";
    }
    else if(duration/60>1){
        double min=0;
        double sec=0;
        std::div_t minResult = std::div(duration,60);
        min=minResult.quot;

        sec=duration-min*60;
        durationResult=QString::number(min)+"分"+QString::number(sec)+"秒";
    }
    else{
        durationResult=QString::number(duration)+"秒";
    }

    QString dateStr=common->GetDateTimeStr();

    sql=QString("Insert into AmplProgram values('%1','False','','','','%2','');").arg(amplGuid,dateStr);
    query.exec(sql);

    sql=QString("update amplProgram set "
                "programName='%1',"
                "Duration='%3',"
                "StepNum=(Select count(*) from AmplStep where ProgramId='%2'),"
                "Memo='%4' "
                "where ID='%2'").arg(ui->programeName->text(),amplGuid,durationResult,ui->lineEdit->text());
    query.exec(sql);

    tcts *tctsWindow = new tcts();
    tctsWindow->infochange("提示","treat","扩增程序信息保存成功",false,true);
    tctsWindow->show();
}

